package mamikeji.liaowa.ui.activity.circle;

import android.app.Dialog;
import android.app.Service;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.facebook.drawee.view.SimpleDraweeView;
import com.google.gson.Gson;
import com.squareup.okhttp.Request;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import jp.wasabeef.glide.transformations.BlurTransformation;
import mamikeji.liaowa.R;
import mamikeji.liaowa.application.MyApplication;
import mamikeji.liaowa.bean.MyCircleBean;
import mamikeji.liaowa.http_api.ForHttp;
import mamikeji.liaowa.http_api.HttpApi;
import mamikeji.liaowa.http_api.HttpKey;
import mamikeji.liaowa.ui.activity.BaseActivity;
import mamikeji.liaowa.ui.activity.right.UserFollowActivity;
import mamikeji.liaowa.ui.adapter.MyCircleAdapter;
import mamikeji.liaowa.utils.ForContents;
import mamikeji.liaowa.utils.ForLog;
import mamikeji.liaowa.utils.ForPreference;
import mamikeji.liaowa.utils.ForToast;
import mamikeji.liaowa.utils.MultiStateView;
import mamikeji.liaowa.widget.floatingactionbutton.FloatingActionButton;
import mamikeji.liaowa.widget.pulltorefresh.PullToRefreshBase;
import mamikeji.liaowa.widget.pulltorefresh.PullToRefreshListView;
import mamikeji.liaowa.widget.refreshView.PtrlDownRefreshFrameLayout;

public class MyCircleActivity extends BaseActivity {
    private static final String TAG = "MyCircleActivity";

    private static final int TAG_CIRCLE = 1001;

    @BindView(R.id.listView_my_circle)
    PullToRefreshListView listViewMyCircle;
    @BindView(R.id.multiple_my_circle_add)
    FloatingActionButton multipleMyCircleADD;
    @BindView(R.id.ptrlDownRefreshFrameLayout_my_circle_diary)
    PtrlDownRefreshFrameLayout ptrlDownRefreshFrameLayoutMyCircleDiary;
    @BindView(R.id.multiStateView_my_circle_diary)
    MultiStateView multiStateViewMyCircleDiary;

    private SimpleDraweeView imageView_my_circle_userimg;
    private TextView textView_my_circle_guanzhu,textView_my_circle_fans;
    private View view_header;
    private ImageView imageView_my_circle_header_bg;

    /**
     * 当前页数
     */
    private int page = 1;
    /**
     * 总页数
     */
    private int maxPage = 0;

    //宝妈圈数据集
    private List<MyCircleBean.DataEntity> myfcList = new ArrayList<>();
    /**
     * 每页的活动数据集合
     */
    ArrayList<MyCircleBean.DataEntity> mList;

    private MyCircleAdapter myCircleAdapter;

    int position_s;
    int fc_id_s;

    private boolean bool_circle_refresh = false;
    private boolean bool_delete = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_circle);
        getBase();
        ButterKnife.bind(this);
        setTitleLeftImage(R.drawable.icon_fanhuibai_n_fff, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (bool_circle_refresh){
                    setResult(RESULT_OK, new Intent());
                }
                finish();
            }
        });
        String nameString = getResources().getString(R.string.mycircle_name);
        String nameFinal = String.format(nameString, ForPreference.getString(ForContents.USER_NAME));
        setTitleName(nameFinal);

        init();
        showDeleteDialog();
        getMain_FriendCircleData(1, 10);
    }

    private void init() {
        bool_circle_refresh = false;
        myCircleAdapter = new MyCircleAdapter(myfcList, this);

        view_header = LayoutInflater.from(MyApplication.getContext()).inflate(R.layout.item_my_circle_header, null);
        listViewMyCircle.getRefreshableView().addHeaderView(view_header, null, false);

        listViewMyCircle.setAdapter(myCircleAdapter);

        imageView_my_circle_header_bg = (ImageView) view_header.findViewById(R.id.imageView_my_circle_header_bg);
        imageView_my_circle_userimg = (SimpleDraweeView) view_header.findViewById(R.id.imageView_my_circle_userimg);
        textView_my_circle_guanzhu = (TextView) view_header.findViewById(R.id.textView_my_circle_guanzhu);
        textView_my_circle_fans = (TextView) view_header.findViewById(R.id.textView_my_circle_fans);

        imageView_my_circle_userimg.setImageURI(Uri.parse(ForPreference.getString(ForContents.USER_HEADERURL)));

        //加载背景，
        Glide.with(MyCircleActivity.this)
                .load(ForPreference.getString(ForContents.USER_HEADERURL))
                .dontAnimate()
                .error(R.drawable.img_baoziliaobeijing)
                // 设置高斯模糊
                .bitmapTransform(new BlurTransformation(MyCircleActivity.this, 14, 2))
                .into(imageView_my_circle_header_bg);

        //关注数
        String guanzhuString = getResources().getString(R.string.mycircle_guanzhu);
        String guanzhuFinal = String.format(guanzhuString, ForPreference.getInt(ForContents.USER_follow));
        textView_my_circle_guanzhu.setText(guanzhuFinal);
        //粉丝数
        String fansString = getResources().getString(R.string.mycircle_fensi);
        String fansFinal = String.format(fansString, ForPreference.getInt(ForContents.USER_fans));
        textView_my_circle_fans.setText(fansFinal);

        textView_my_circle_guanzhu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MyCircleActivity.this, UserFollowActivity.class);
                intent.putExtra(ForContents.USER_follow, ForPreference.getString(ForContents.USER_CODE));
                intent.putExtra("type", true);
                intent.putExtra(ForContents.USER_NAME, ForPreference.getString(ForContents.USER_NAME));
                startActivity(intent);
            }
        });

        textView_my_circle_fans.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MyCircleActivity.this, UserFollowActivity.class);
                intent.putExtra(ForContents.USER_follow, ForPreference.getString(ForContents.USER_CODE));
                intent.putExtra("type", false);
                intent.putExtra(ForContents.USER_NAME, ForPreference.getString(ForContents.USER_NAME));
                startActivity(intent);
            }
        });

        listViewMyCircle.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (!myCircleAdapter.bool_delete) {
                    Intent intent = new Intent(MyCircleActivity.this, CircleDetailsActivity.class);
                    intent.putExtra("fcid", myfcList.get(i - 2).getFcid() + "");
                    startActivityForResult(intent, TAG_CIRCLE);
                }
            }
        });

        multiStateViewMyCircleDiary.getView(MultiStateView.VIEW_STATE_ERROR).findViewById(R.id.button_error_refish)
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        multiStateViewMyCircleDiary.setViewState(MultiStateView.VIEW_STATE_LOADING);
                        getMain_FriendCircleData(1, 10);
                    }
                });

        multiStateViewMyCircleDiary.setEmptyText(R.string.mycircle_add).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivityForResult(new Intent(MyCircleActivity.this, PublishCircleActivity.class), TAG_CIRCLE);
            }
        });

        ptrlDownRefreshFrameLayoutMyCircleDiary.setPtrHandler(new PtrDefaultHandler() {
            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, listViewMyCircle.getRefreshableView(), header);
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                getMain_FriendCircleData(1, 10);
            }
        });

        listViewMyCircle.setMode(PullToRefreshBase.Mode.PULL_FROM_END);
        listViewMyCircle.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            //下拉刷新数据
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
            }

            //上拉加载更多
            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                if (++page >= maxPage) {
                    new Handler().postDelayed(new Runnable() {
                        public void run() {
                            listViewMyCircle.onRefreshComplete();
                            ForToast.showToast(R.string.error_down_end);
                        }
                    }, 1000);
                } else {
                    getMain_FriendCircleData(page, 10);
                }
            }
        });

        multipleMyCircleADD.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivityForResult(new Intent(MyCircleActivity.this,PublishCircleActivity.class),TAG_CIRCLE);
            }
        });

        myCircleAdapter.setOnItemClickListener(new MyCircleAdapter.OnItemClickListener() {
            @Override
            public void onZanClick(int fc_id, int position) {
                getFabulousCircle(fc_id + "", position);
            }

            @Override
            public void onDeleteClick(int fc_id, int position) {
                position_s = position;
                fc_id_s = fc_id;
                dialog_delete.show();
            }
        });

        imageView_my_circle_userimg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ArrayList<String> urlList = new ArrayList<>();
                urlList.add(ForPreference.getString(ForContents.USER_HEADERURL));
                Intent intent = new Intent(MyCircleActivity.this, PreviewCircleImgActivity.class);
                intent.putStringArrayListExtra("urlList", urlList);
                intent.putExtra("position", 1);
                intent.putExtra("img_url", true);
                startActivity(intent);
            }
        });
    }

    private void getMain_FriendCircleData(int index, int size) {
        //参数集合
        Map<String, String> formMap = new HashMap<String, String>();
        formMap.put(HttpKey.FC_INDEXPAGE, index + "");
        formMap.put(HttpKey.FC_PAGESIZE, size + "");
        formMap.put(HttpKey.FC_TYPE, "1");
        formMap.put(HttpKey.FC_USERCODE, ForPreference.getString(ForContents.USER_CODE));
        ForHttp.setMsg(HttpApi.ROOT_PATH + HttpApi.FRIEND_MY_CIRCLE_DATE, formMap, new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {
                ForLog.i(TAG, e.getMessage().toString());
                ForToast.showToast(R.string.intent_error);
                multiStateViewMyCircleDiary.setViewState(MultiStateView.VIEW_STATE_NOINTERNET);
                listViewMyCircle.onRefreshComplete();
                ptrlDownRefreshFrameLayoutMyCircleDiary.refreshComplete();
            }

            @Override
            public void onResponse(String response) {
                ForLog.i(TAG, response);
                listViewMyCircle.onRefreshComplete();
                ptrlDownRefreshFrameLayoutMyCircleDiary.refreshComplete();
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String status = jsonObject.getString(HttpKey.STATUS);
                    if ("200".equals(status)) {
                        MyCircleBean bean = new Gson().fromJson(response, MyCircleBean.class);
                        if (bean.getData().size() > 0) {
                            setTitleRightImage(R.drawable.icon_shanchunaozhong_n, new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    if (bool_delete){
                                        /**震动服务*/
                                        Vibrator vib = (Vibrator) getSystemService(Service.VIBRATOR_SERVICE);
                                        vib.vibrate(50);//只震动一秒，一次

                                        myCircleAdapter.bool_delete = !myCircleAdapter.bool_delete;
                                        myCircleAdapter.notifyDataSetChanged();
                                    }
                                }
                            });

                            mList = new ArrayList<MyCircleBean.DataEntity>();
                            mList = (ArrayList<MyCircleBean.DataEntity>) bean.getData();

                            if (page == 1) {
                                bool_delete = true;
                                maxPage = bean.getTotal();
                                myfcList.clear();
                                myfcList.addAll(mList);
                                myCircleAdapter.setList(myfcList);
                            } else {
                                myfcList.addAll(mList);
                                myCircleAdapter.notifyDataSetChanged();
                            }
                            multiStateViewMyCircleDiary.setViewState(MultiStateView.VIEW_STATE_CONTENT);
                        } else {
                            if (page == 1)
                                multiStateViewMyCircleDiary.setViewState(MultiStateView.VIEW_STATE_EMPTY);
                        }
                    } else {
                        multiStateViewMyCircleDiary.setViewState(MultiStateView.VIEW_STATE_ERROR);
                        ForToast.showToast(jsonObject.getString(HttpKey.MESSAGE));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void getDelete_FriendCircleData() {
        showLoading();
        //参数集合
        Map<String, String> formMap = new HashMap<String, String>();
        formMap.put(HttpKey.FC_delete_USERCODE, ForPreference.getString(ForContents.USER_CODE));
        formMap.put(HttpKey.FC_delete_FCID, fc_id_s + "");
        ForHttp.setMsg(HttpApi.ROOT_PATH + HttpApi.FRIEND_MY_CIRCLE_DELETE, formMap, new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {
                ForLog.i(TAG, e.getMessage().toString());
                ForToast.showToast(R.string.intent_error);
                listViewMyCircle.onRefreshComplete();
                ptrlDownRefreshFrameLayoutMyCircleDiary.refreshComplete();
                hideLoading();
            }

            @Override
            public void onResponse(String response) {
                ForLog.i(TAG, response);
                listViewMyCircle.onRefreshComplete();
                ptrlDownRefreshFrameLayoutMyCircleDiary.refreshComplete();
                hideLoading();
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String status = jsonObject.getString(HttpKey.STATUS);
                    if ("200".equals(status)) {
                        ForToast.showToast("已删除！");
                        int num = ForPreference.getInt(ForContents.USER_my_circle) - 1;
                        ForPreference.putInt(ForContents.USER_my_circle , num);
                        bool_circle_refresh = true;
                        myfcList.remove(position_s);
                        myCircleAdapter.notifyDataSetChanged();
                    } else {
                        ForToast.showToast(jsonObject.getString(HttpKey.MESSAGE));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private Dialog dialog_delete;
    private RelativeLayout relativeLayout_clock_dig_query, relativeLayout_clock_dig_btnerror;

    /**
     * 确认删除
     */
    private void showDeleteDialog() {
        dialog_delete = new Dialog(MyCircleActivity.this, R.style.DialogLoading);
        View inflate = LayoutInflater.from(MyCircleActivity.this).inflate(R.layout.diglog_clock_delete, null);
        dialog_delete.setContentView(inflate);

        relativeLayout_clock_dig_query = (RelativeLayout) inflate.findViewById(R.id.relativeLayout_clock_dig_query);
        relativeLayout_clock_dig_btnerror = (RelativeLayout) inflate.findViewById(R.id.relativeLayout_clock_dig_btnerror);

        relativeLayout_clock_dig_query.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog_delete.hide();

                getDelete_FriendCircleData();
            }
        });
        relativeLayout_clock_dig_btnerror.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog_delete.hide();
            }
        });
    }

    /**
     * 点赞
     */
    private void getFabulousCircle(final String fcid, final int position) {
        showLoading();
        //参数集合
        Map<String, String> formMap = new HashMap<String, String>();
        formMap.put(HttpKey.FC_PRAISE_USERCODE, ForPreference.getString(ForContents.USER_CODE));
        formMap.put(HttpKey.FC_PRAISE_FCID, fcid);
        formMap.put(HttpKey.FC_PRAISE_TYPE, "2");
        ForHttp.setMsg(HttpApi.ROOT_PATH + HttpApi.FRIEND_CIRCLE_PRAISE, formMap, new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {
                ForToast.showToast(R.string.intent_error);
                hideLoading();
            }

            @Override
            public void onResponse(String response) {
                hideLoading();
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String status = jsonObject.getString(HttpKey.STATUS);
                    if ("200".equals(status)) {
                        bool_circle_refresh = true;
                        int num = myfcList.get(position).getPraisenumber();
                        if (myfcList.get(position).getPraisestate() == 1) {
                            myfcList.get(position).setPraisestate(0);
                            myfcList.get(position).setPraisenumber(--num);
                        } else {
                            myfcList.get(position).setPraisestate(1);
                            myfcList.get(position).setPraisenumber(++num);
                        }
                        myCircleAdapter.notifyDataSetChanged();
                    } else {
                        ForToast.showToast(jsonObject.getString(HttpKey.MESSAGE));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == TAG_CIRCLE) {
                bool_circle_refresh = true;
                //获取朋友圈
                getMain_FriendCircleData(1, 10);
            }
        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        //关注数
        String guanzhuString = getResources().getString(R.string.mycircle_guanzhu);
        String guanzhuFinal = String.format(guanzhuString, ForPreference.getInt(ForContents.USER_follow));
        textView_my_circle_guanzhu.setText(guanzhuFinal);
        //粉丝数
        String fansString = getResources().getString(R.string.mycircle_fensi);
        String fansFinal = String.format(fansString, ForPreference.getInt(ForContents.USER_fans));
        textView_my_circle_fans.setText(fansFinal);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if(bool_circle_refresh){
                setResult(RESULT_OK, new Intent());
            }
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

}
